//
//  MTNewClubAreaCell.swift
//  MT
//
//  Created by ooops on 2020/5/10.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import Foundation
import Eureka
import MTCategory

public final class MTNewClubEditAreaRow: MTNewClubAreaCellEditRow, RowType {
    required public init(tag: String?) {
        super.init(tag: tag)
    }
}

open class MTNewClubAreaCellEditRow: MTNewClubAreaCellRow {
    required public init(tag: String?) {
        super.init(tag: tag)
    }
}

open class MTNewClubAreaCell: Cell<String>, CellType {
    
    private var provinces: [ProvinceModel]?
    private var provinceIndex: Int = 0
    private var cityIndex: Int = 0
    private var areaIndex: Int = 0

    public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    lazy var pickerView: UIPickerView = {
        let pickerView = UIPickerView()
        pickerView.delegate = self
        pickerView.dataSource = self
        //pickerView.tintAdjustmentMode = .automatic
        pickerView.backgroundColor = UIColor.white
        return pickerView
    }()

    /// 显示模式
    lazy var tipLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(14)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "名称"
        l.textAlignment = .right
        l.setContentHuggingPriority(.defaultHigh, for: .horizontal)
        return l
    }()
    
    lazy var contentLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCRegularFont(14)
        l.textColor = UIColor.text.x9b9b9b
        l.numberOfLines = 0
        l.lineBreakMode = .byCharWrapping
        l.textAlignment = .right
        return l
    }()
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.seprateLine.x707070
        v.isHidden = true
        return v
    }()
    
    lazy var customAccessoryView: UIImageView = {
            let imageV = UIImageView(image: UIImage(named: "icon_right_gary"))
            return imageV
        }()
    
    public var tipString: String? = nil
    public var contentString: String? = nil
    /// 输入框提示文字
    public var placeholder: String? {
        didSet {
            if placeholder != nil {
                let attribute: [NSAttributedString.Key : Any] = [NSAttributedString.Key.font : PingFangSCMediumFont(14),
                                                                 NSAttributedString.Key.foregroundColor : UIColor.text.x9b9b9b];
                contentLabel.attributedText = NSAttributedString(string: placeholder!, attributes: attribute)
            }
        }
    }
    
    public var isHiddenAccessory: Bool = true {
        didSet {
            customAccessoryView.isHidden = isHiddenAccessory
        }
    }
    
    public var accessoryImage: String? {
        didSet {
            if accessoryImage != nil {
                customAccessoryView.image = UIImage(named: accessoryImage!)
            } else {
                customAccessoryView.image = nil
            }
        }
    }
    
    private var isHiddenLineView: Bool = true {
        didSet {
            lineView.isHidden = isHiddenLineView
        }
    }
    
    public var isEditMode: Bool = false {
        didSet {
            lineView.isHidden = !isEditMode
            isHiddenAccessory = !isEditMode
        }
    }
    
    private var rowValue: String? {
        didSet {
            self.contentLabel.text = rowValue
            row.value = rowValue
        }
    }
    
    open override func setup() {
        super.setup()
        backgroundColor = UIColor.theme.background
        selectionStyle = .none
        textLabel?.isHidden = true
        detailTextLabel?.isHidden = true
        editingAccessoryType =  .none
        
        contentView.addSubview(tipLabel)
        contentView.addSubview(contentLabel)
        contentView.addSubview(lineView)
        contentView.addSubview(customAccessoryView)
        
        makeConstraint()
        
        let path = Bundle.main.path(forResource: "ProvincesAndCities", ofType: "plist")
        if let plistPath = path, let array = NSArray(contentsOfFile: plistPath) as? [[String:Any]] {
            var provinces: [ProvinceModel] = []
            for a in array {
                let p = ProvinceModel(dict: a)
                provinces.append(p)
            }
            self.provinces = provinces
            
            pickerView.reloadAllComponents()
        }
    }
    
    private func makeConstraint() {
        lineView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(0.5)
            make.bottom.equalToSuperview()
        }
        
        tipLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.width.greaterThanOrEqualTo(30)
        }
        
        contentLabel.snp.makeConstraints { (make) in
            make.right.equalTo(customAccessoryView.snp.left).offset(-8)
            make.left.equalTo(tipLabel.snp.right).offset(14)
            make.centerY.equalTo(tipLabel)
        }

        customAccessoryView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-8)
            make.centerY.equalTo(tipLabel)
            make.width.height.equalTo(15)
        }
    }

    deinit {
//        datePicker.removeTarget(self, action: nil, for: .allEvents)
    }

    open override func update() {
        super.update()
        tipLabel.text = tipString
        if row.value != nil {
            contentLabel.text = row.displayValueFor?(row.value)
            contentLabel.font = PingFangSCSemiboldFont(14)
            contentLabel.textColor = UIColor.text.x9b9b9b
        }
    }

    open override func didSelect() {
        super.didSelect()
        row.deselect()
    }

    override open var inputView: UIView? {
        if isEditMode {
            return pickerView
        }
        return nil
    }

    @objc func datePickerValueChanged(_ sender: UIDatePicker) {
        contentLabel.text = row.displayValueFor?(row.value)
    }
    open override func cellCanBecomeFirstResponder() -> Bool {
        return canBecomeFirstResponder
    }

    override open var canBecomeFirstResponder: Bool {
        return isEditMode
    }
    
    open override func resignFirstResponder() -> Bool {
        if self.row.value != nil {
            _ = self.pickerView(self.pickerView, titleForRow: provinceIndex, forComponent: 0)
            _ = self.pickerView(self.pickerView, titleForRow: cityIndex, forComponent: 1)
            _ = self.pickerView(self.pickerView, titleForRow: areaIndex, forComponent: 2)
            return super.resignFirstResponder()
        }
        let province = provinces?[provinceIndex].province
        let city = provinces?[provinceIndex].cities?[cityIndex].name
        let area = provinces?[provinceIndex].cities?[cityIndex].areas?[areaIndex]
        var name = ""
        if let province = province {
            name += province + "-"
        }
        if let city = city {
            name += city + "-"
        }
        if let area = area {
            name += area
        }
        // clubAddressInput.contentTextField.text = name
        self.rowValue = name
        return super.resignFirstResponder()
    }
}

// MARK: ------------------ UIPickerViewDelegate ----------------------
extension MTNewClubAreaCell: UIPickerViewDelegate {
    
    public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0 {
            provinceIndex = row
            cityIndex = 0
            areaIndex = 0
            pickerView.reloadComponent(1)
            pickerView.reloadComponent(2)
        } else if component == 1 {
            cityIndex = row
            areaIndex = 0
            pickerView.reloadComponent(2)
        } else {
            areaIndex = row
        }
        let province = provinces?[provinceIndex].province
        let city = provinces?[provinceIndex].cities?[cityIndex].name
        let area = provinces?[provinceIndex].cities?[cityIndex].areas?[areaIndex]
        var name = ""
        if let province = province {
            name += province + "-"
        }
        if let city = city {
            name += city + "-"
        }
        if let area = area {
            name += area
        }
        // clubAddressInput.contentTextField.text = name
        self.rowValue = name
    }
}

// MARK: ------------------ UIPickerViewDataSource ----------------------
extension MTNewClubAreaCell: UIPickerViewDataSource {
 
    public func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }
    
    public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return provinces?.count ?? 0
        } else if component == 1 {
            return provinces?[provinceIndex].cities?.count ?? 0
        } else {
            return provinces?[provinceIndex].cities?[cityIndex].areas?.count ?? 0
        }
    }
    
    public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if component == 0 {
            return provinces?[row].province ?? ""
        } else if component == 1 {
            return provinces?[provinceIndex].cities?[row].name ?? ""
        } else {
            return provinces?[provinceIndex].cities?[cityIndex].areas?[row] ?? ""
        }
    }
    
    public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        
        for(i, v) in pickerView.subviews.enumerated() {
            if v.frame.height < 1 {
                v.backgroundColor = .clear
            }
        }
        
        var pickerLabel = view as? UILabel
        if pickerLabel == nil {
            pickerLabel = UILabel()
            pickerLabel?.textColor = UIColor.text.x1d1a1a
            pickerLabel?.font = PingFangSCSemiboldFont(16)
            pickerLabel?.textAlignment = .center
            pickerLabel?.backgroundColor = .white
        }
        pickerLabel?.text = self.pickerView(pickerView, titleForRow: row, forComponent: component)
        return pickerLabel!
    }
    
}

open class MTNewClubAreaCellRow: Row<MTNewClubAreaCell>, NoValueDisplayTextConformance {

    open var noValueDisplayText: String? = nil

    required public init(tag: String?) {
        super.init(tag: tag)
        displayValueFor = { [unowned self] value in
            guard let val = value else { return nil }
            return val
        }
    }
}

